/**
 * @Title: HomeActivity.java
 * @Package com.sinoglobal.waitingMe.activity
 * @Description: TODO(用一句话描述该文件做什么)
 * @author hpq
 * @date 2015-8-30 上午11:55:09
 */

package com.sinoglobal.wallet.activity;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.activity.W_RechargeDetailsActivity.DestoryRechargeDetailsReciver;
import com.sinoglobal.wallet.adapter.W_RechargeRecordAdapter;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.entity.W_Bkjson;
import com.sinoglobal.wallet.entity.W_RechargeRecordItemEntity;
import com.sinoglobal.wallet.entity.W_RechargeRecordItemRsEntity;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.NetWorkUtil;
import com.sinoglobal.wallet.view.pulltorefresh.WPullToRefreshView;
import com.sinoglobal.wallet.view.pulltorefresh.WPullToRefreshView.OnFooterRefreshListener;
import com.sinoglobal.wallet.view.pulltorefresh.WPullToRefreshView.OnHeaderRefreshListener;



/**
 * @author clf
 * @createdate 2015-10-26
 * @Description: TODO(充值记录)
 */
public class W_RechargeRecordActivity extends W_SinoBaseActivity implements OnFooterRefreshListener, OnHeaderRefreshListener {
	private W_RechargeRecordItemEntity rechargeRecord;
	private WPullToRefreshView recharge_record_pulltorefresh;
	private ListView recharge_record_listview;
	private W_RechargeRecordAdapter adapter;
	private List<W_RechargeRecordItemRsEntity> list=new  ArrayList<W_RechargeRecordItemRsEntity>();
	private String Type="2";//充值记录界面标示
	private int payState=-1;
	private int payStyle=-1;//支付方式
	private boolean isShowProgressDialog=true;
    private int page=1;
    private String count="10";
    private int totalpages;//总页数
    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
	private LinearLayout rechargeRecord_nodata_layout;  //无数据时展示页面
	private UpdateRechargeRecordReciver RechargeRecordReciver;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.wallet_recharge_record_layout);
		mTemplateTitleText.setText("充值记录");
		initView();
		getData();
	}
	private void initView() {
		// TODO Auto-generated method stub
		adapter=new W_RechargeRecordAdapter(this);
		recharge_record_pulltorefresh = (WPullToRefreshView) findViewById(R.id.recharge_record_pulltorefresh);
		recharge_record_listview = (ListView) findViewById(R.id.recharge_record_listview);
		rechargeRecord_nodata_layout = (LinearLayout) findViewById(R.id.rechargeRecord_nodata_layout);
		recharge_record_pulltorefresh.setOnFooterRefreshListener(this);
		recharge_record_pulltorefresh.setOnHeaderRefreshListener(this); 
		recharge_record_listview.setAdapter(adapter);
		//baldetail_help_layout.setVisibility(View.VISIBLE);
		//baldetail_pulltorefresh.setVisibility(View.GONE);
		recharge_record_listview.setOnItemClickListener(new OnItemClickListener() {
			

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				W_RechargeRecordItemRsEntity entity=list.get(position);
				int payType = Integer.valueOf(entity.getPayType());//payType;//支付方式：1：余额、2：支付宝、3：U付、4：微信
				String payStatus = entity.getPayStatus();
				String amount = entity.getAmount();
				W_Bkjson bkjson = entity.getBkjson();
				long time = entity.getCreateDate();
				String orderSn = entity.getOrderSn();
				Bundle bundle = new Bundle();
			     bundle.putString("Code", entity.getCode());
			     bundle.putString("Source", "Record");
			     bundle.putInt("PayStyle", payType);
			     bundle.putString("PayState", payStatus);
			     bundle.putString("Time",sdf.format(new Date(time)));
			   bundle.putSerializable("Bkjson", bkjson);
		         bundle.putString("Money", amount);
		         bundle.putString("OrderSn", orderSn);
				goIntent(W_RechargeRecordDetailsActivity.class, bundle);
			}
		});
		initReciver();
	}
	/**
	 * 注册更新充值记录状态的广播
	 */
	private void initReciver() {
		// TODO Auto-generated method stub
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(SinoConstans.KEY_UpdateReceiver);
		RechargeRecordReciver = new UpdateRechargeRecordReciver();
		registerReceiver(RechargeRecordReciver, intentFilter);
	}
	@Override
	public void onHeaderRefresh(WPullToRefreshView view) {
		recharge_record_pulltorefresh.setEnablePullLoadMoreDataStatus(true);
		isShowProgressDialog=false;
		page=1;
		getData();
	}
	@Override
	public void onFooterRefresh(WPullToRefreshView view) {
		isShowProgressDialog=false;
		if (page <=totalpages) {
			getData();
		
		} else {
			Toast.makeText(W_RechargeRecordActivity.this, "没有更多数据了", Toast.LENGTH_SHORT).show();
			recharge_record_pulltorefresh.setEnablePullLoadMoreDataStatus(false);
			recharge_record_pulltorefresh.onFooterRefreshComplete();
		}
	}
	private void getData() {
		MyAsyncTask<W_RechargeRecordItemEntity> task = new MyAsyncTask<W_RechargeRecordItemEntity>(true,this,true) {
			@Override
			public W_RechargeRecordItemEntity before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getChargeLog(W_RechargeRecordActivity.this, page+"", count);
			}

			@Override
			public void after(W_RechargeRecordItemEntity result) {
			
				if (result != null) {
					if (result.getCode().equals("100")) {
						
						  loadError(false);
						  if (page == 1){
							if(result.getRs().size()==0){
								rechargeRecord_nodata_layout.setVisibility(View.VISIBLE);
								return;
							} }
							rechargeRecord_nodata_layout.setVisibility(View.GONE);
							if (page == 1) {
								list=result.getRs();
			                        adapter.setListData(list);
			                      
			                    } else {
			                    	list.addAll(result.getRs());
			                    }
						
									adapter.setListData(list);
								
								
									   totalpages = result.getNum();
								
								page++;
								recharge_record_pulltorefresh.onFooterRefreshComplete();
								recharge_record_pulltorefresh.onHeaderRefreshComplete();
					}else{
						recharge_record_pulltorefresh.onFooterRefreshComplete();
						recharge_record_pulltorefresh.onHeaderRefreshComplete();
						Toast.makeText(W_RechargeRecordActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}else{
					recharge_record_pulltorefresh.onFooterRefreshComplete();
					recharge_record_pulltorefresh.onHeaderRefreshComplete();
					Toast.makeText(W_RechargeRecordActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
				}
				
			}

			@Override
			public void exception() {
			}
		};
		task.execute();
	}
		

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		 if(id==R.id.wallet_noData){
			 if(NetWorkUtil.getNetWorkInfoType(getApplicationContext())==NetWorkUtil.NONE){
				showToast("请检查网络是否连接！");	
				 loadError(true);
				}else{
					loadError(false);;
					getData();
				}
			}		 
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(RechargeRecordReciver);//充值详情的广播取消
	}
    /**
     * 修改订单的状态
     * @param seatId
     */
    public  void updateOrderStateList(String orderSn,String isRecharge){
        for (W_RechargeRecordItemRsEntity rechargeRecorditem :list){
            if(rechargeRecorditem.getOrderSn().equals(orderSn)){
            	if("1".equals(isRecharge)){
            		rechargeRecorditem.setPayStatus("1");//更改订单状态为成功
				}else if("3".equals(isRecharge)){
					rechargeRecorditem.setPayStatus("4");//更改订单状态为充值中
				}
            	
            	
                LogUtils.v("进来了");

            }
        }
        adapter.setListData(list);
    }
	public  class UpdateRechargeRecordReciver extends BroadcastReceiver {


		public  UpdateRechargeRecordReciver(){

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(SinoConstans.KEY_UpdateReceiver)){
				String isRecharge = intent.getStringExtra("isRecharge");
				String orderSn = intent.getStringExtra("orderSn");
				if("1".equals(isRecharge)||"3".equals(isRecharge)){
					updateOrderStateList(orderSn,isRecharge);
				}
			}

		}
	}
}
